package com.codingfuture.erp_system.service.impl;

import com.codingfuture.erp_system.dto.MarketDetailDto;
import com.codingfuture.erp_system.dto.MarketDto;
import com.codingfuture.erp_system.dto.OrdersDetailDto;
import com.codingfuture.erp_system.entity.Role;
import com.codingfuture.erp_system.entity.Supplier;
import com.codingfuture.erp_system.mapper.MarketMapper;
import com.codingfuture.erp_system.service.MarketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class MarketServiceImpl implements MarketService {
    @Autowired
    private MarketMapper marketMapper;

    @Override
    public List<MarketDto> findByAll() {
        return marketMapper.findByAll();
    }

    @Override
    public List<MarketDetailDto> findMarketDetailDto(long uuid) {
        return marketMapper.findMarketDetailDto(uuid);
    }

    @Override
    public List<Supplier> showSupplier(Integer type) {
        return marketMapper.showSupplier(type);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addMarketDetail(List<MarketDetailDto> marketDetails) {
        return marketMapper.addMarketDetail(marketDetails);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addById(MarketDto marketDto) {
        return marketMapper.addById(marketDto);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean doOutStore(Integer id, Date date, Integer storeuuid) {
        int num = marketMapper.doOutStore(id, date, storeuuid);
        int i = 1;
        List<OrdersDetailDto> list = marketMapper.findById(id);
        for (OrdersDetailDto ordersDetailDto : list) {
            Long ordersuuid = ordersDetailDto.getOrdersuuid();
            List<OrdersDetailDto> ordersDetailDtoList = marketMapper.findByUuid(ordersuuid);
            for (OrdersDetailDto detailDto : ordersDetailDtoList) {
                String state = detailDto.getState();
                if (Objects.equals(state, "0")) {
                    return i != 0;
                } else {
                    i = marketMapper.updateByState(ordersuuid);
                }
            }
        }
        return num != 0 && i != 0;
    }

    @Override
    public Role findId(Object name) {
        return marketMapper.findId(name);
    }


}
